import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Radio,
  InputNumber,
  Switch,
  message,
  Space,
  Popconfirm,
} from "antd";
import {
  createMenuApi,
  getParentMenu,
  getMenuList,
  updateMenuApi,
  deleteMenuApi,
} from "../../api/menu";
import * as AntdIcons from "@ant-design/icons";
import { useSelector } from "react-redux";
import styled from "styled-components";

// 使用 styled-components 创建带主题的组件
const StyledDiv = styled.div`
  background-color: ${(props) => props.theme.backgroundColor};
  color: ${(props) => props.theme.textColor};
`;

const StyledButton = styled(Button)`
  &.ant-btn-primary {
    background-color: ${(props) => props.theme.primaryColor};
    border-color: ${(props) => props.theme.primaryColor};
    color: #fff;
    &:hover,
    &:focus {
      background-color: ${(props) => props.theme.primaryColorHover};
      border-color: ${(props) => props.theme.primaryColorHover};
    }
  }
`;

const MenuManage = () => {
  console.log("MenuManage component is rendering"); // 调试日志

  const [menuList, setMenuList] = useState([]);
  const [parentMenus, setParentMenus] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingMenu, setEditingMenu] = useState(null);
  const [form] = Form.useForm();

  const { currentTheme } = useSelector((state) => state.layout);

  useEffect(() => {
    fetchMenuList();
    fetchParentMenus();
  }, []);

  const fetchMenuList = async () => {
    try {
      const response = await getMenuList();
      setMenuList(response.data);
    } catch (error) {
      console.error("获取菜单列表失败:", error);
      message.error("获取菜单列表失败");
    }
  };

  const fetchParentMenus = async () => {
    try {
      const response = await getParentMenu();
      setParentMenus(response.data);
    } catch (error) {
      console.error("获取父级菜单失败:", error);
      message.error("获取父级菜单失败");
    }
  };

  const showModal = (menu = null) => {
    setEditingMenu(menu);
    if (menu) {
      form.setFieldsValue({
        menuType: menu.menuType,
        menuName: menu.menuName,
        parentId: menu.parentId,
        path: menu.path,
        component: menu.component,
        icon: menu.icon,
        sortOrder: menu.sortOrder,
        isRoute: menu.isRoute === 1,
        isHidden: menu.isHidden === 1,
        isCached: menu.isCached === 1,
        permissions: menu.permissions,
      });
    } else {
      form.resetFields();
    }
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setEditingMenu(null);
    form.resetFields();
  };

  const handleSubmit = async (values) => {
    try {
      const submittingValues = {
        ...values,
        isRoute: values.isRoute ? 1 : 0,
        isHidden: values.isHidden ? 1 : 0,
        isCached: values.isCached ? 1 : 0,
      };

      if (editingMenu) {
        await updateMenuApi(editingMenu.id, submittingValues);
        message.success("更新菜单成功");
      } else {
        await createMenuApi(submittingValues);
        message.success("创建菜单成功");
      }
      setIsModalOpen(false);
      form.resetFields();
      fetchMenuList();
    } catch (error) {
      console.error("操作失败:", error);
      message.error("操作失败");
    }
  };

  const handleDelete = async (id) => {
    try {
      await deleteMenuApi(id);
      message.success("删除菜单成功");
      fetchMenuList();
    } catch (error) {
      console.error("删除菜单失败:", error);
      message.error("删除菜单失败");
    }
  };

  const iconList = Object.keys(AntdIcons)
    .filter(
      (key) =>
        key.endsWith("Outlined") ||
        key.endsWith("Filled") ||
        key.endsWith("TwoTone")
    )
    .sort();

  const iconOptions = iconList.map((iconName) => ({
    label: (
      <Space>
        <span>{iconName}</span>
        {React.createElement(AntdIcons[iconName])}
      </Space>
    ),
    value: iconName,
  }));

  const columns = [
    {
      title: "菜单名称",
      dataIndex: "menuName",
      key: "menuName",
      render: (text, record) => {
        const indent = record.parentId ? "└ " : "";
        return (
          <span>
            {indent}
            {text}
          </span>
        );
      },
    },
    { title: "路径", dataIndex: "path", key: "path" },
    {
      title: "图标",
      dataIndex: "icon",
      key: "icon",
      render: (icon) => {
        const IconComponent = AntdIcons[icon];
        return IconComponent ? <IconComponent /> : icon;
      },
    },
    { title: "排序", dataIndex: "sortOrder", key: "sortOrder" },
    {
      title: "菜单类型",
      dataIndex: "menuType",
      key: "menuType",
      render: (text) => (text === "TOP_MENU" ? "一级菜单" : "子菜单"),
    },
    {
      title: "是否为路由",
      dataIndex: "isRoute",
      key: "isRoute",
      render: (value) => (value === 1 ? "是" : "否"),
    },
    {
      title: "是否隐藏",
      dataIndex: "isHidden",
      key: "isHidden",
      render: (value) => (value === 1 ? "是" : "否"),
    },
    {
      title: "是否缓存",
      dataIndex: "isCached",
      key: "isCached",
      render: (value) => (value === 1 ? "是" : "否"),
    },
    { title: "权限", dataIndex: "permissions", key: "permissions" },
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <Space size="middle">
          <StyledButton
            icon={<AntdIcons.EditOutlined />}
            onClick={() => showModal(record)}
            theme={currentTheme}
          >
            修改
          </StyledButton>
          <Popconfirm
            title="确定要删除这个菜单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <StyledButton
              icon={<AntdIcons.DeleteOutlined />}
              danger
              theme={currentTheme}
            >
              删除
            </StyledButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <StyledDiv theme={currentTheme}>
      <StyledButton
        type="primary"
        onClick={() => showModal()}
        style={{ marginBottom: 16 }}
        theme={currentTheme}
      >
        新增菜单
      </StyledButton>
      <Table
        columns={columns}
        dataSource={menuList}
        rowKey="id"
        pagination={false}
        expandable={{
          childrenColumnName: "children",
          defaultExpandAllRows: true,
        }}
      />

      <Modal
        title={editingMenu ? "修改菜单" : "新增菜单"}
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
          initialValues={{
            menuType: "TOP_MENU",
            isRoute: true,
            isHidden: false,
            isCached: false,
            permissions: "USER",
          }}
        >
          <Form.Item
            name="menuType"
            label="菜单类型"
            rules={[{ required: true, message: "请选择菜单类型" }]}
          >
            <Radio.Group>
              <Radio value="TOP_MENU">一级菜单</Radio>
              <Radio value="SUB_MENU">子菜单</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="menuName"
            label="菜单名称"
            rules={[{ required: true, message: "请输入菜单名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.menuType !== currentValues.menuType
            }
          >
            {({ getFieldValue }) =>
              getFieldValue("menuType") === "SUB_MENU" ? (
                <Form.Item
                  name="parentId"
                  label="上级菜单"
                  rules={[{ required: true, message: "请选择上级菜单" }]}
                >
                  <Select>
                    {parentMenus.map((menu) => (
                      <Select.Option key={menu.id} value={menu.id}>
                        {menu.menuName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: "请输入路径" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="component" label="组件">
            <Input />
          </Form.Item>
          <Form.Item
            name="icon"
            label="图标"
            rules={[{ required: true, message: "请选择图标" }]}
          >
            <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) =>
                option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {iconOptions.map((option) => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="sortOrder"
            label="排序"
            rules={[{ required: true, message: "请输入排序" }]}
          >
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item name="isRoute" label="是否为路由" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item name="isHidden" label="是否隐藏" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item name="isCached" label="是否缓存" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item
            name="permissions"
            label="权限"
            rules={[{ required: true, message: "请选择权限" }]}
          >
            <Select>
              <Select.Option value="USER">用户</Select.Option>
              <Select.Option value="ADMIN">管理员</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <StyledButton type="primary" htmlType="submit" theme={currentTheme}>
              {editingMenu ? "更新" : "创建"}
            </StyledButton>
          </Form.Item>
        </Form>
      </Modal>
    </StyledDiv>
  );
};

export default MenuManage;
